package com.jack006.api.interceptors;

import com.jack006.enums.UserStatus;
import com.jack006.exception.GraceException;
import com.jack006.grace.result.ResponseStatusEnum;
import com.jack006.pojo.AppUser;
import com.jack006.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname UserActiveInterceptor
 * @Description 用户激活状态检查拦截器
 * 发文章、修改文章、删除文章
 * 发表评论，查看评论等等
 * 这些接口都是需要用户激活之后才能进行，
 * 否则需要提示用户前往【账号设置】去修改信息
 * @Date 2021-06-14 16:44
 * @Created by jack
 */
public class UserActiveInterceptor  extends BaseInterceptor implements HandlerInterceptor {

    /**
     * 拦截请求进入 controller 之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userId = request.getHeader("headerUserId");
        String userJson = redisOperator.get(REDIS_USER_INFO+":"+userId);
        AppUser appUser = null;
        if (StringUtils.isNotBlank(userJson)) {
            appUser = JsonUtils.jsonToPojo(userJson,AppUser.class);
        } else {
            GraceException.display(ResponseStatusEnum.UN_LOGIN);
            return false;
        }

        if (appUser.getActiveStatus() == null
                || appUser.getActiveStatus() != UserStatus.ACTIVE.type) {
            GraceException.display(ResponseStatusEnum.USER_INACTIVE_ERROR);
            return false;
        }

        /**
         * false: 请求被拦截
         * true： 请求通过验证，放行
         */

        return true;
    }

    /**
     * 在请求访问到 controller,渲染视图之后
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在请求访问到 controller,渲染视图之后
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
